import { ref } from 'vue';

import { preferences } from '@vben/preferences';
import { isEmpty } from '@vben/utils';

import { defineStore } from 'pinia';

import { getSettingUpload } from '#/api/admin/setting';
import { getAdminSetting } from '#/api/setting';

export const usePreferencesStore = defineStore('preferences', () => {
  const appName = localStorage.getItem('$_app_name') ?? preferences.app.name;
  const title = ref(appName);
  const uploadSetting = ref<any>({});
  // 获取上传设置
  const getUploadSetting = async () => {
    if (isEmpty(uploadSetting.value)) {
      const { data } = await getSettingUpload();
      uploadSetting.value = data.setting;
      return uploadSetting.value;
    } else {
      return uploadSetting.value;
    }
  };
  const setTitle = (newTitle: string) => {
    title.value = newTitle;
    localStorage.setItem('$_app_name', title.value);
  };
  const getAppInfo = async () => {
    const { data } = await getAdminSetting();
    title.value = data?.admin_settings?.admin_name ?? preferences.app.name;
    setTitle(title.value);
  };

  const $reset = () => {
    title.value = appName;
  };

  return {
    title,
    setTitle,
    getAppInfo,
    getUploadSetting,
    uploadSetting,
    $reset,
  };
});
